<?php
// 登录用户
include '../../init.php';

// 注册信息
if (empty($_POST)) {
	show_msg(1, '数据不能为空', 3, 'index.php');
	exit();
}

// 验证验证码
$post_code = getV($_POST, 'login_validate_code');
$loca_code = getV($_SESSION, 'login_validate_code');
if (strtolower($post_code) != strtolower($loca_code)) {
	show_msg(1, '校验码不正确');
	exit();
}

// 校对数据
$account = getV($_POST, 'account');
$pwd = getV($_POST, 'password');
$qid = getV($_POST, 'questionid');
$answer = getV($_POST, 'answer');
if (empty($account) || empty($pwd)) {
	show_msg(1, '必填数据不能为空');
	exit();
}

// 数据库校验
$sql = "SELECT uid,password,status,isAdmin,isStop,last_time FROM `login_tb` WHERE account='" . $account . "' LIMIT 1 ;";
$users = array();
my_mysql_query($sql, $users);

if (count($users[0])<1) {
	show_msg(1, '用户名不存在', 30);
	exit();
}
list($uid,$mypwd,$status,$isAdmin,$isStop,$last_time) = array_values($users[0]);
if ($mypwd != md5($pwd)) {
	show_msg(1, '用户名密码不匹配');
	exit();
}

if ($status == 1) {
	show_msg(1, '账户被冻结不好用');
	exit();
}

$sql = "SELECT email,alias,avatarid,qid,answer FROM `userinfo_tb` WHERE uid=" . $uid . " LIMIT 1 ;";
$array = array();
my_mysql_query($sql, $array);
list($email,$alias,$avatar,$myqid,$myanse) = array_values($array[0]);
if (($myqid != $qid) || ($answer != $myanse)) {
	show_msg(1, '安全问题不对');
	exit();
}

// 保存登录数据,
$time = getV($_POST, 'remember');
if ($time) {
	$time = 7*24*60*60;
	setCookie('is_login', true, time() + $time, '/');
	setCookie('account', $account, time() + $time, '/');
	setCookie('password', $mypwd, time() + $time, '/');
}

// 更新数据库时间
$current_time = time();
$sql = "UPDATE `login_tb` SET last_time=".$current_time."  WHERE uid=".$uid;
my_mysql_query($sql, $array);
// 要确定是否是今天第一次登陆,最后登陆时间一天不是同一天就好了
if (date('d',$last_time) != date('d',$current_time)) {
	addscore($uid, 2);
}

$_SESSION['uid'] = $uid;
$_SESSION['alias'] = $alias;
$_SESSION['avatar'] = $avatar;
$_SESSION['email'] = $email;
$_SESSION['qid'] = $myqid;
$_SESSION['answer'] = $myanse;
$_SESSION['is_login'] = true;
$_SESSION['isAdmin'] = $isAdmin;
$_SESSION['isStop'] = $isStop;

// 销毁session中的校对码
unset($_SESSION['login_validate_code']);

show_msg(0, '欢迎回来:'.$alias, 1, '../../index.php');
